package svc

import (
	"common/comRedis"
	"common/mysql"
	"fmt"
	"github.com/go-redis/redis/v8"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"service/internal/config"
	"time"
)

type ServiceContext struct {
	Config config.Config
	DB     *gorm.DB
	Rdb    *redis.Client
}

func NewServiceContext(c config.Config) *ServiceContext {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		c.MYSQL.USER,
		c.MYSQL.PWD,
		c.MYSQL.HOST,
		c.MYSQL.PORT,
		c.MYSQL.Database)
	fg := gorm.Config{
		Logger: logger.New(log.Default(), logger.Config{
			SlowThreshold:             200 * time.Millisecond,
			Colorful:                  true,
			IgnoreRecordNotFoundError: false,
			LogLevel:                  logger.Info,
		}),
	}
	DB := mysql.InitMysql(dsn, &fg)
	Rdb := comRedis.GetRdb(&c.ServerRedis)
	return &ServiceContext{
		Config: c,
		DB:     DB,
		Rdb:    Rdb,
	}
}
